const nodemailer = require('nodemailer')
var express = require('express');
var router = express.Router();
const MailModels = require('../../models/mailModels')


//邮件配置,不需要变动
const transporter = nodemailer.createTransport({
    host: 'smtp.qq.com',
    port:465,
    auth:{
        user: '3367589938@qq.com', //qq邮箱
        pass: 'ujhtxetjzklucheh' //授权码
    }
})
//生成6位随机数
function generateRandomNumber() {
    let randomNumber = '';
    for (let i = 0; i < 6; i++) {
        randomNumber += Math.floor(Math.random() * 10);
    }
    return randomNumber;
}

router.post('/', async (req, res, next) => {
    let verification = generateRandomNumber()
    // console.log(mailCode)
    // console.log('req.body.email')
    let mailOption={
        from: '3367589938@qq.com',  //发送人邮箱
        to: req.body.email,  //收件人邮箱
        subject: '验证码', //邮件主题
        text: verification
    }
    
    transporter.sendMail(mailOption,(err,info) => {
        if(err) {
            res.json({
                code: '1005',
                msg: '发送失败',
                data: err
              })
        }else {
            res.json({
                code: '0000',
                msg: '发送成功',
                data: null
              })
        }
    })

    MailModels.create({verification}).then(ress => {
        console.log(ress)
    }).catch(err => {
        console.log(err)
    }) 
    setTimeout(async (verification) => {  
        await MailModels.deleteOne({ verification });  
    }, 60000, verification); // 注意这里将verification作为额外的参数传递给setTimeout
    
});
 


module.exports = router;
